<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>SpringBoot实现广播式WebSocket</title>
    <script src="./js/sockjs.min.js"></script>
    <script src="./js/stomp.js"></script>
    <script src="./js/jquery-3.1.1.js"></script>
</head>
<body>
<noscript><h2 style="color:#ff0000">抱歉,您的浏览器不支持该功能!</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">连接</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
    </div>
    <div id="conversationDiv">
        <label>请输入您的姓名</label><input type="text" id="name" />
        <br>
        <label>请输入您发送的消息</label><input  type="text" id ="chatContent"/>
        <br>
        <label>请输入你的房间号</label><input  type="text" id = "roomId"/>
        <br>
        <button id="sendMessage" onclick="sendMessage();">发送</button>
        <br>
        <textarea id="response"></textarea>
    </div>
</div>
</body>
<script type="text/javascript">
    var ws;
    function setConnected(connected){
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        $("#response").html();
    }
    function connect(){
        var roomId = $('#roomId').val();
        ws = new WebSocket('ws://localhost:8777/ws-service/websocket');
        ws.onopen = WSonOpen;
        ws.onmessage = WSonMessage;
        ws.onclose = WSonClose;
        ws.onerror = WSonError;
    }
    function WSonOpen() {
        var message = {
            name:'Server',
            chatContent:'成功连接'
        }
        setConnected(true);
        showResponse(message)
    };
    function WSonMessage(event) {
        var message = {
            name:'Server',
            chatContent:event.data
        }
        showResponse(message)
    };
    function WSonClose() {
        var message = {
            name:'Server',
            chatContent:'已断开'
        }
        showResponse(message)
    };
    function WSonError() {
        var message = {
            name:'Server',
            chatContent:'连接错误！'
        }
        showResponse(message)
    };
    function disconnect(){
        ws.close()
        setConnected(false);
        console.log("Disconnected");
    }
    function sendMessage(){
        var chatContent = $("#chatContent").val();
        var roomId = $('#roomId').val();
        ws.send(JSON.stringify({'roomId':roomId,'chatContent':chatContent}))
    }
    function showResponse(message){
        var response = $("#response").val();
        $("#response").val(response+message.name+': '+message.chatContent+'\n');
    }
</script>
</html>